/**
 * CORS中间件配置
 * 处理跨域请求
 */
const cors = require('koa-cors');

/**
 * 配置CORS中间件
 * @returns {Function} CORS中间件函数
 */
const corsMiddleware = () => {
  return cors({
    origin: (ctx) => {
      // 开发环境允许所有来源
      if (process.env.NODE_ENV === 'development') {
        return '*';
      }
      
      // 生产环境可以配置具体的域名
      const allowedOrigins = [
        'http://localhost:5173',
        'http://localhost:3000',
        'http://127.0.0.1:5173',
        'http://127.0.0.1:3000'
      ];
      
      const origin = ctx.request.header.origin;
      return allowedOrigins.includes(origin) ? origin : false;
    },
    credentials: true,
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Requested-With']
  });
};

module.exports = corsMiddleware;